package com.runen.wnhz.runen.ui.activity.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.SearchResultBean;
import com.runen.wnhz.runen.common.utils.NetStateUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.ui.activity.BasicActivity;
import com.runen.wnhz.runen.ui.activity.major.CourseDetailsActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.SearchResultAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class SearchResultActivity extends BasicActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.list_searchResult)
    ListView listSearchResult;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;
    private int totalPage;
    private int currentPage = 0;
    private boolean hasNextPage = false;
    private String so,type;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;
    private List<SearchResultBean.DataBean.ListBean> listBeans;
    private SearchResultAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
        ButterKnife.bind(this);
        listBeans = new ArrayList<>();
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        setListener();
        setData();
    }

    private void setData() {
        so = getIntent().getStringExtra("so");
        type =  getIntent().getStringExtra("type");
        if (so != null) {
            showProgressDialog();
            editSearch.setText(so);
            getLessonList(so, String.valueOf(currentPage));
        }
    }

    private void setListener() {
        smartRefreshLayout.setEnableAutoLoadMore(false);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (NetStateUtils.isNetworkAvalible(SearchResultActivity.this)) {
                    if (hasNextPage) {
                        int tempCurrentPage = currentPage + 1;
                        isLoadMore = true;
                        getLessonList(so, String.valueOf(tempCurrentPage));
                    } else {
                        ToastUtil.showToast("暂无更多数据");
                        smartRefreshLayout.finishLoadMore(true);
                    }
                } else {
                    smartRefreshLayout.finishLoadMore(false);
                    ToastUtil.showToast("暂无网络");
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (NetStateUtils.isNetworkAvalible(SearchResultActivity.this)) {
                    int tempCurrentPage = 0;
                    isRefresh = true;
                    getLessonList(so, String.valueOf(tempCurrentPage));
                } else {
                    smartRefreshLayout.finishRefresh(false);
                    ToastUtil.showToast("暂无网络");
                }
            }
        });
      listSearchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
              Intent intent = new Intent(SearchResultActivity.this, CourseDetailsActivity.class);
              SearchResultBean.DataBean.ListBean listBean = listBeans.get(position);
              if(listBean != null) {
                  intent.putExtra("lid",listBean.getLid());
              }
              startActivity(intent);
          }
      });
    }

    @OnClick(R.id.iv_back)
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void getLessonList(String so, String pageNum) {
        FormBody formBody;
        if(null != so && !so.equals("")){
         formBody = new FormBody.Builder().add("type", type).add("page", pageNum).add("search", so).build();
        }else{
             formBody = new FormBody.Builder().add("type", type).add("page", pageNum).build();
        }
        //构建一个网络请求，从指定网址上面请求数据
        Request.Builder requestBuilder = new Request.Builder().url(NetUtils.USER_SEARCH_CONTENT_URL).post(formBody);
        //创建Call对象
        Call newCall = OkHttpUtils.getOkHttpClient().newCall(requestBuilder.build());
        newCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showToast("请求数据失败");
                        if(isRefresh) {
                            smartRefreshLayout.finishRefresh(false);
                            isRefresh = false;
                        }
                        if(isLoadMore){
                            smartRefreshLayout.finishLoadMore(false);
                            isLoadMore = false;
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            handleData(response);
                        } catch (IOException e) {
                            ToastUtil.showToast("数据请求出现异常");
                            e.printStackTrace();
                            if(isRefresh) {
                                smartRefreshLayout.finishRefresh(false);
                                isRefresh = false;
                            }
                            if(isLoadMore){
                                smartRefreshLayout.finishLoadMore(false);
                                isLoadMore = false;
                            }
                        }
                    }
                });
            }
        });
    }

    private void handleData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            String json = responseBody.string();
            SearchResultBean searchResultBean = new Gson().fromJson(json, SearchResultBean.class);
            currentPage = Integer.parseInt(searchResultBean.getData().getPage());//当前页数
            totalPage = Integer.parseInt(searchResultBean.getData().getSum_page());//总页数
            if ("1".equals(searchResultBean.getData().getIs_page())) {
                hasNextPage = true;
            } else {
                hasNextPage = false;
            }
            dismissDialog();
            if ("0".equals(searchResultBean.getRe())) {
                ToastUtil.showToast(searchResultBean.getInfo());
                if(isRefresh){
                    smartRefreshLayout.finishRefresh(true);
                    isRefresh = false;
                }
                if(isLoadMore){
                    smartRefreshLayout.finishLoadMore(true);
                    isLoadMore = false;
                }
            } else if ("1".equals(searchResultBean.getRe())) {
                if (isRefresh) {
                    if(searchResultBean.getData().getList().size() != 0){
                        currentPage = 0;
                    }
                    smartRefreshLayout.finishRefresh(true);
                    if (listBeans.size() != 0) {
                        listBeans.clear();
                    }
                    listBeans.addAll(searchResultBean.getData().getList());
                    if (adapter == null) {
                        adapter = new SearchResultAdapter(listBeans, SearchResultActivity.this);
                        listSearchResult.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                    isRefresh = false;
                    return;
                }
                if (isLoadMore) {
                    if(searchResultBean.getData().getList().size() != 0){
                        currentPage = currentPage + 1;
                    }
                    smartRefreshLayout.finishLoadMore(true);
                    listBeans.addAll(searchResultBean.getData().getList());
                    if (adapter == null) {
                        adapter = new SearchResultAdapter(listBeans, SearchResultActivity.this);
                        listSearchResult.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                    isLoadMore = false;
                    return;
                }
                listBeans.addAll(searchResultBean.getData().getList());
                adapter = new SearchResultAdapter(listBeans, SearchResultActivity.this);
                listSearchResult.setAdapter(adapter);
            }
        }
    }
}
